package com.homegoods.designer.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.homegoods.designer.R;
import com.homegoods.designer.adapter.ItemNeedTouGaoAdapter;
import com.homegoods.designer.databinding.DesignerActivityEditSpaceBinding;
import com.homegoods.designer.event.EditSpaceEvent;
import com.homegoods.designer.model.EditDesignCase2Model;
import com.homegoods.aroutercomment.ARouterPath;
import com.kedll.library.addimg.ViewImgFragmentActivity01;
import com.kedll.library.base.MyBaseFragmentActivity;
import com.kedll.library.contants.OnItemClickListener;
import com.kedll.library.crop.TakePhotoHelper;
import com.kedll.library.mvp.BasePresenter;
import com.kedll.library.util.CollectionUtils;
import com.kedll.library.util.Parse;
import com.kedll.library.util.RxBus;
import com.kedll.library.util.StringUtil;
import com.kedll.library.util.ToastUtil;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.RuntimePermissions;

/**
 * @author QiQi
 * @ClassName: EditSpaceActivity
 * @date 2018/10/7
 * @description
 */
@RuntimePermissions
@Route(path = ARouterPath.PATH_EDIT_SPACE)
public class EditSpaceActivity extends MyBaseFragmentActivity<DesignerActivityEditSpaceBinding, BasePresenter> implements OnItemClickListener {

    public static final int MAX_COUNT = 9;
    @Autowired(name = "space")
    public EditDesignCase2Model model;

    @Autowired(name = "index")
    public int index;

    ItemNeedTouGaoAdapter adapter;
    /**
     * 添加图片的Item
     */
    Map<String, Object> addMap = new HashMap<>();
    private TakePhotoHelper photoHelper;

    @Override
    protected int getLayout() {
        return R.layout.designer_activity_edit_space;
    }

    @Override
    protected void initEvent() {
        adapter.setOnItemClickListener(this);
        photoHelper.setOnTakePhotoCompleteListener(picStr -> {
            adapter.clear();
            adapter.addAll(photoHelper.getImagesDatas());

            if (CollectionUtils.size(photoHelper.getImagesDatas()) < MAX_COUNT) {
                if (!adapter.getValues().contains(addMap)) {
                    adapter.getValues().add(addMap);
                }
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EditSpaceActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @SuppressLint("CheckResult")
    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        photoHelper = new TakePhotoHelper(this);
        photoHelper.setIsCrop(false);
        adapter = new ItemNeedTouGaoAdapter(getApplicationContext());

        if (CollectionUtils.isNotEmpty(model.getPics())) {
            Observable.fromIterable(model.getPics())
                    .compose(bindToLifecycle())
                    .map(path -> {
                        Map<String, Object> map = new HashMap<>(2);
                        map.put("imagePath", path);
                        map.put("isCheck", true);
                        photoHelper.initImageDatas(map);
                        return map;
                    })
                    .toList()
                    .subscribe(maps -> adapter.addAll(maps));
        }

        if (CollectionUtils.size(model.getPics()) < MAX_COUNT) {
            addMap.put("isAdd", true);
            adapter.add(addMap);
        }
        mBinding.pics.setAdapter(adapter);
    }

    @Override
    protected void initToolBar(Bundle savedInstanceState) {
        super.initToolBar(savedInstanceState);
        ARouter.getInstance().inject(this);
        setTitle(model.getTitle());
        mBinding.etDescription.setText(model.getDescrip());
        int length = StringUtil.strLength(model.getDescrip());
        if (length > 0) {
            mBinding.etDescription.setSelection(length);
        }

        setTopRightButton("保存", v -> {
            if (TextUtils.isEmpty(mBinding.etDescription.getText())) {
                ToastUtil.showToast("请填写描述");
                return;
            }

            model.setDescrip(mBinding.etDescription.getText().toString());
            List<String> pics = new ArrayList<>();
            for (int i = 0; i < adapter.getCount(); i++) {
                Map<String, Object> map = adapter.getItem(i);
                String imgPath = Parse.getInstance().isNull(map.get("imagePath"));
                if (StringUtil.isNotEmpty(imgPath)) {
                    pics.add(imgPath);
                }
            }
            model.setPics(pics);

            EditSpaceEvent event = new EditSpaceEvent(model, index);
            RxBus.getDefault()
                    .post(event);
            finish();

        });
    }

    @Override
    protected BasePresenter getPresenter() {
        return null;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        photoHelper.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void itemClick(View v, Map<String, Object> item, int position) {
        int i = v.getId();
        if (i == R.id.iv_add_photo) {
            //添加图片
            EditSpaceActivityPermissionsDispatcher.onTakePhotoWithPermissionCheck(this);

        } else if (i == R.id.iv_del_photo) {
            //删除图片
            photoHelper.removeImage(item);
            adapter.remove(item);
            if (!adapter.getValues().contains(addMap)) {
                adapter.getValues().add(addMap);
            }

        } else if (i == R.id.iv_photo) {
            //查看大图
            Intent intent = new Intent(this, ViewImgFragmentActivity01.class);
            intent.putExtra("selectedList", (Serializable) adapter.getValues());
            intent.putExtra("current", position);
            startActivity(intent);
            overridePendingTransition(enterAnim, exitAnim);

        } else {
        }
    }

    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void onTakePhoto() {
        photoHelper.showPopup(MAX_COUNT);
    }
}
